<?php
namespace Swoole\Socket;

use Common\Log;
class SocketClient{
    protected $iClient;
//     private $config;
    protected $host;
    protected $port;
    protected $serv;

    function __construct($iClent, $host, $port){
        Log::info("SocketClient __construct $host:$port ");
        $args_num = func_num_args();
        $this->host = $host;
        $this->port = $port;
        $this->iClient = $iClent;
        
    }
    
    private function initSocket(){
        $this->serv = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
        $this->serv->on("Connect", array($this->iClient, "onConnect"));
        $this->serv->on("Receive", array($this->iClient, "onReceive"));
        
        $this->serv->on("Error", array($this->iClient, "onError"));
        $this->serv->on("Close", array($this->iClient, "onClose"));
        
        $this->serv->set(array(
            'open_eof_check' => true,
            'package_eof' => "\r\n"
        ));
    }
    function connect()
    {
        
        //Log::info("1connect====".gettype($this->serv) . __LINE__);
        if(empty($this->serv) == true || gettype($this->serv) != 'object'){
            $this->initSocket();
        }
        //Log::info("2connect====".gettype($this->serv));
//         if($this->serv instanceof swoole_client){
            $this->serv->connect($this->host, $this->port, - 1);
//             if ($this->serv->connect($this->host, $this->port, - 1) == false) {
//                 echo __CLASS__ . " connect failed {$this->host}:{$this->port}. Error: \n";
//             }
//         }
        
        //echo "SocketClient connect to registry {$this->host}:{$this->port} \n";
    }
    
    public function isConnected(){
        //echo "isConnected=================".gettype($this->serv);
        //var_dump($this->serv);
        //Log::info("isConnected====".gettype($this->serv));
        //Log::info("isConnected======".empty($this->serv).",".($this->serv instanceof swoole_client));
        //var_dump($this->serv);
        if(gettype($this->serv) == 'object'){
            
            return $this->serv->isConnected();
        }
        else{
            return false;
        }
    }
    public function send($data){
        $this->serv->send($data);
    }
    public function close(){
        return $this->serv->close();
    }
}

?>